const Koa = require("koa");
const path = require("path");
const app = new Koa();
const views = require("koa-views");
const json = require("koa-json");
const onerror = require("koa-onerror");
// const bodyparser = require('koa-bodyparser')
const logger = require("koa-logger");
// 上传文件用
const koaBody = require("koa-body");
// 引入跨域配置文件
const config = require("./config/index.js");
// 解决跨域
const cors = require("koa2-cors");
// 引入中间件
const { routerResponse } = require("./middleware/index.js");
const { verifyToken } = require("./utils/token.js");
const jwt = require("koa-jwt");

const index = require("./routes/index");
const users = require("./routes/usersRouter");
const blog = require("./routes/blogRouter");
const adminRouter = require("./routes/admin");
const update = require("./routes/updateRouter"); // token验证
// const publicIp = require('public-ip');  // 获取IP
// const {
// 	sendemailA
// } = require('./db/function/sendEmail')
// app.use(async (ctx, next) => {
// 	var token = ctx.headers.authorization;
// 	console.log('token', token);
// 	if (token == undefined) {
// 		await next();
// 	} else {
// 		verifyToken(token).then((data) => {
// 			//这一步是为了把解析出来的用户信息存入全局state中，这样在其他任一中间价都可以获取到state中的值
// 			ctx.state = {
// 				data
// 			};
// 		})
// 		await next();
// 	}
// })
// 使用koa-body上传文件 替代koa-parser
app.use(
  koaBody({
    multipart: true,
    formidable: {
      maxFileSize: 200 * 1024 * 1024, // 设置上传文件大小最大限制，默认2M
      uploadDir: path.join(__dirname, "public/"), // 设置文件上传目录
      keepExtensions: true, // 保持文件的后缀
      onFileBegin: (name, file) => {
        // 文件上传前的设置
        console.log(`name: ${name}`);
        console.log(file);
      },
    },
  })
);
// 发送IP
// publicIp.v4().then(ip => {
// 	console.log(ip);
// 	//=> '46.5.21.123'
// 	sendemailA('ip地址',ip).then(res=>{
// 		console.log('发送成功');
// 	})
// });
// 跨域设置
if (config.isCross) {
  console.log("开启跨域");
  app.use(cors());
  // app.use(cross({
  //     allowOrigin:['*'],
  //     allowMethods:[],
  //     allowHeaders:[]
  // }))
  //跨域设置
}
// jwt 错判处理
app.use((ctx, next) => {
  return next().catch((err) => {
    if (err.status == 401) {
      ctx.body = {
        code: 401,
        msg: "登录过期，请重新登录。",
      };
    } else {
      throw err;
    }
  });
});
// error handler
onerror(app);
app.use(
  jwt({
    secret: config.tokenKey,
  }).unless({
    path: [
      /\/getblogDetail/,
      /\/sendemail/,
      /\/getblogs/,
      /\/user\/createUser/,
      /\/user\/login/,
    ],
  })
);
// middlewares
// app.use(bodyparser({
// 	enableTypes: ['json', 'form', 'text']
// }))

app.use(json());
app.use(logger());
app.use(require("koa-static")(__dirname + "/public"));

app.use(
  views(__dirname + "/views", {
    extension: "pug",
  })
);

// logger
app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

// app.use(verifyToken())
// 引入中间件
app.use(
  routerResponse({
    successCode: config.successCode,
    failCode: config.failCode,
    failMsg: config.failMsg,
    successMsg: config.successMsg,
  })
);
// routes
app.use(index.routes(), index.allowedMethods());
app.use(users.routes(), users.allowedMethods());
app.use(blog.routes(), blog.allowedMethods());
app.use(update.routes(), update.allowedMethods());
app.use(adminRouter.routes(), adminRouter.allowedMethods());
// error-handling
app.on("error", (err, ctx) => {
  console.error("server error", err, ctx);
});

module.exports = app;
